<script lang="ts">
  import { onMount } from 'svelte';
  import { writable } from 'svelte/store';
  import { getExchangeRates, type Rates } from './utils/api';
  import "./styles/styled.css"
  import InputAtom from './lib/InputAtom/InputAtom.svelte';
  import SelectAtom from "./lib/SelectAtom/Select.svelte"

  // Хранилища для данных
  const rates = writable<Rates>({});
  const amount1 = writable<string>("1");
  const amount2 = writable<string>("2");
  const currency1 = writable<string>('USD');
  const currency2 = writable<string>('RUB');

  onMount(async () => {
    const ratesData = await getExchangeRates();
    rates.set(ratesData);
  });

  // Реактивные вычисления для конвертации валют
  $: if ($rates && $currency1 && $currency2 && $rates[$currency1] && $rates[$currency2]) {
    const rate1 = $rates[$currency1];
    const rate2 = $rates[$currency2];
    const isAmount1Updated = lastUpdatedField === 'amount1';

    const numAmount1 = parseFloat($amount1);
    const numAmount2 = parseFloat($amount2);

    if (!isNaN(numAmount1) && !isNaN(numAmount2)) {
      if (isAmount1Updated) {
        amount2.set(((numAmount1 * rate2) / rate1).toString());
      } else {
        amount1.set(((numAmount2 * rate1) / rate2).toString());
      }
    }
  }

  // Для предотвращения цикличных обновлений, нужно контролировать, какое поле последнее обновлялось
  let lastUpdatedField = 'amount1';

  function handleAmount1Change(event: CustomEvent<number>): void {
    lastUpdatedField = 'amount1';
    amount1.set(event.detail);
  }

  function handleAmount2Change(event: CustomEvent<number>): void {
    lastUpdatedField = 'amount2';
    amount2.set(event.detail);
  }
</script>

<main class="mainContainer">
  <header class="center" style="margin-bottom: 30px;"><h2>Конвертер Валют</h2></header>
  <div class="container">
    <div class="converter_input">
      <InputAtom bind:value={$amount1} on:change={handleAmount1Change} />
      <SelectAtom options={Object.keys($rates)} bind:selected={$currency1} on:select={value => currency1.set(value)} />
    </div>
    <div class="converter_input">
      <InputAtom bind:value={$amount2} on:change={handleAmount2Change}/>
      <SelectAtom options={Object.keys($rates)} bind:selected={$currency2} on:select={value => currency2.set(value)} />
    </div>
  </div>
</main>
<footer class="center">
  <a target="_blank" rel="noopener noreferrer" href="https://t.me/ivan_veetsok"><h4 class="font-medium cursor-pointer uppercase styled_h4__kU5EZ leading-[100%] tracking-normal not-italic break-words text-h4 font-regular ">© Ivan Veetsok</h4></a>
</footer>
